class Solution {
public:
    vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
         vector<int> res(numCourses);
        vector<unordered_set<int>> g(numCourses);
        vector<int> indegrees(numCourses);
        for (auto prerequisite : prerequisites) {
            int w = prerequisite[0];
            int v = prerequisite[1];
            g[v].insert(w);
            indegrees[w]++;
        }
        queue<int> q;
        for (int i = 0; i < numCourses; i++) {
            if (indegrees[i] == 0) {
                q.push(i);
            }
        }
        int index = 0;
        while (!q.empty()) {
             int v = q.front();
            q.pop();
            res[index++] = v;
            for (int w : g[v]) {
                indegrees[w]--;
                if (indegrees[w] == 0) {
                    q.push(w);
                }
            }
        }
        if (index != numCourses) {
            res.clear();
        }
        return res;
    }
};